#include "D20Model.h"
#include "defines.h"
#include "Skill.h"
#include "Feat.h"
#include "Special.h"
#include "CharacterClass.h"


#include <XmlSerializer.h>


#include <QFile>



D20Model::D20Model(QObject *parent) :
    ItemModel(parent)
{
}


QModelIndex D20Model::addSkill()
{
    QModelIndex parent = group("Skills");
    int row = createItem<Skill>(tr("New Skill"), parent);

    return index(row, AbstractItem::NameData, parent);
}


QModelIndex D20Model::addSubSkill(const QString &skill)
{
    QModelIndex parent = group(QString("Skills.%1").arg(skill));
    int row = createItem<Skill>(tr("New %1 Subskill").arg(skill), parent);

    return index(row, AbstractItem::NameData, parent);
}


QModelIndex D20Model::addSpecial()
{
    QModelIndex parent = group("Special Abilities");
    int row = createItem<Special>(tr("New Special Ability"), parent);

    return index(row, AbstractItem::NameData, parent);
}


QModelIndex D20Model::addFeat()
{
    QModelIndex parent = group("Feats");
    int row = createItem<Feat>(tr("New Feat"), parent);

    return index(row, AbstractItem::NameData, parent);
}



QModelIndex D20Model::addBaseBonus()
{
    QModelIndex parent = group("Base Bonuses");
    int row = createItem<BaseBonus>(tr("New Base Bonus"), parent);

    return index(row, AbstractItem::NameData, parent);
}


QModelIndex D20Model::addCharacterClass()
{
    QModelIndex parent = group("Character Classes");
    if (!parent.isValid()) return QModelIndex();

    QFile file(":/d20/CHARACTER_CLASS");
    if (!file.open(QFile::ReadOnly)) return QModelIndex();

    XmlSerializer serializer;
    CharacterClass* item = dynamic_cast<CharacterClass*>(serializer.deserialize(&file));
    if (!item) return QModelIndex();

    int row = addItem(item, parent);

    return index(row, AbstractItem::NameData, parent);
}



QModelIndex D20Model::group(QString name) const
{
    if (!name.startsWith(".")) name = QString(".%1").arg(name);

    QModelIndex search = index(0, AbstractItem::IdData, QModelIndex());
    QModelIndexList found = match(search,
                                  Qt::EditRole,
                                  name,
                                  1,
                                  Qt::MatchEndsWith | Qt::MatchRecursive);


    if (found.isEmpty()) return QModelIndex();

    return found.first();
}


